<script>
    $(document).ready(function() {
    	  window.mode = "";

				// callback that receives the updates from the Server
				window.onItemUpdate = function (itemPos, updateInfo, itemName) {
				  var message = updateInfo.getNewValue("message");
				  var timestamp = updateInfo.getNewValue("time");
				  var player = updateInfo.getNewValue("player");
				  var playerId = updateInfo.getNewValue("player_id");

				  console.log("AVATAR" + avatarMap[playerId]);
				  processUpdate(playerId, message, timestamp, player, "chat_message", avatarMap[playerId]);
				};

				window.processUpdate = function(playerId, message, timestamp, player, playType, avatar) {
          if (playerId == "{{ profile.id }}") {
            player = "Me";
          }

          var hide = "";
          if (window.mode != "" && playType != window.mode) {
        	  hide = "hide";
          }

          $("<div style='margin-bottom:10px' class='message_display " + playType + " " + hide + "'>" +
          "<span style='display:inline-block;width:30px; margin-right:7px;vertical-align:top'><img src='" + avatar + "' style='height:30px; margin-right: 2px'" +
          " class='avatar_of_" + playerId + "'></span>" + "<span style='display:inline-block;max-width:160px'><b><span class='username_of_" + playerId +
          "'>" + player + "</span>" + "</b><br>" + message +
            "</span><p style='color:#888; font-size: x-small; margin:0px; text-align:right;border-bottom: 1px solid #ddd;'>" + timestamp + "</p></div>").appendTo("#messages");
          doScroll();
          getCardImages();
				}

        $("#message_entry").keypress(function(event) {
            var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
            if (keycode == 13) {
            	event.preventDefault();
            	var message = $("#message_entry").val();
            	if (message.length > 0) {
            		var metadata = ["message:" + message];
            		$.post("/makePlay/", {"play_type":"chat_message", "game_id":'{{ game.id }}', "metadata": metadata});
	              var now = new Date();
	              var mex = "CHAT|{{ game.id }}|" + message + "|{{ profile.name }}|" + dateFormat(now, "h:MM TT")
	                + "|{{ profile.id }}|";
	              engineRef.sendMessage(mex, null, 5000);
	              $("#message_entry").val("");
            	}
            }
        });

        $("#play_tab").click(function() {
        	$(".message_display").show();
        	$(".chat_message").hide();
        	window.mode = "game";
        	doScroll();
        });

        $("#chat_tab").click(function() {
           $(".message_display").hide();
           $(".chat_message").show();
           window.mode = "chat_message";
           doScroll();
        });

        $("#chat_play_tab").click(function() {
           $(".message_display").show();
           window.mode = "";
           doScroll();
        });

        window.getCardImages = function() {
        	$("#messages").find("*").each(function () {
       		   while ($(this).html().indexOf("card_image_") != -1) {
               var patt = /card_image_[a-z0-9_]*/i;
               var fullText = $(this).html().match(patt)[0];
               var text = fullText.replace("card_image_", "");
               var newHTML = $(this).html().replace(fullText,
            	     "<img style='width: 20px; margin-right: 2px' src='/site_media/images/cards/" + text + ".png'>");
               newHTML = newHTML.replace(" card<img", " card<br><img");
               newHTML = newHTML.replace(" card <img", " card<br><img");
               $(this).html(newHTML);
       		   }
       		});
        }

        function doScroll() {
        	$('#messages').clearQueue();
        	$('#messages').stop();
        	$('#messages').animate({
        		scrollTop: $('#messages').get(0).scrollHeight}, 500);
        }

        getCardImages();
        $("#chat_play_tab").click();

        if (navigator.userAgent.indexOf("Firefox")!=-1) {
        	$("#message_entry").css("height", "67px");
        }

        {% load custom_filters %}
        {% for message in game.play_set.all %}
          {% with message|getMetadata:"message" as message_text %}
            {% with message.play_type as play_type %}
              {% if message_text and not message|getMetadata:"is_standby" %}
                processUpdate("{{ message.player.id }}", "{{ message_text }}",
                  "{{message.creation_timestamp|date:'g:i A'}}", "{{ message.player.name }}",
                  "{{ play_type }}", "{{ message.player|getMetadata:'avatar_img' }}");
              {% endif %}
            {% endwith %}
          {% endwith %}
        {% endfor %}
        doScroll();
    });
</script>
<ul class="nav nav-tabs" style="margin-bottom: 5px; margin-top: 0px">
  <li><a id="chat_tab" href="#messages" data-toggle="tab">Chat</a></li>
  <li><a id="play_tab" href="#messages" data-toggle="tab">Plays</a></li>
  <li class="active"><a id="chat_play_tab" href="#messages" data-toggle="tab">All Activity</a></li>
</ul>
<div id="messages" style="height: 333px;overflow:auto;margin-bottom: 5px; padding: 5px; padding-left: 0px">
</div>
<div id="new_message">
    <textarea placeholder="Message" name="message_entry" id="message_entry"
      style="width: 210px;resize:none;height: 70px;"></textarea>
</div>
